package com.szpx.utils.fileutils;

import ch.qos.logback.core.util.FileUtil;
import com.szpx.utils.jsonutils.ApiResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UploadFileUtil {

    @Value("${file.path}")
    private String savePath;

    @Value("${file.previewPath}")
    private String previewPath;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public ApiResult uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResult.error(500, "文件不能为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        try {
            Date date = new Date();
            // 生成路径
            String relativeDir = getRelativeDir(date);
            // 创建文件路径
            File fileDir = new File(savePath + relativeDir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            //新的文件名
            String newName = format(date, "HHmmssSSS") + Math.round(Math.random() * 8999 + 1000) + fileName.substring(fileName.lastIndexOf("."));
            // 新文件路径+新文件名
            String filePath = relativeDir + newName;
            // 保存文件
            file.transferTo(new File(savePath + filePath));
            return ApiResult.success(previewPath + filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error(500,"图片上传发生未知异常，请联系管理员！");
        }
    }

    /**
     * 文件预览吗
     *
     * @param path
     * @param response
     * @throws Exception
     */
    public void filePreview(String path, HttpServletResponse response) {
        response.reset();
        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(new File(savePath + path));
            // 在线打开方式 文件名应该编码成UTF-8
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(String.valueOf(System.currentTimeMillis()), "UTF-8"));
            byte[] buffer = new byte[1024];
            int len;
            outputStream = response.getOutputStream();
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 生成相对路径
     * @param date
     * @return
     */
    public static String getRelativeDir(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        // 文件路径 upload/groupID/年月日
        String monthStr = month < 10 ? "0" + month : "" + month;
        String dayStr = day < 10 ? "0" + day : "" + day;
        String filePath = year + monthStr + dayStr;
        return filePath;
    }

    /**
     * 日期格式胡
     * @param date
     * @param format
     * @return
     */
    public static String format(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }
}
